﻿using AutoMapper;
using B.S.Traceable.Domain.Entitiy;
using B.S.Traceable.ErrorCode;
using B.S.Traceable.Infrasturcture.Interfaces;
using B.S.Traceable.Read.Api.Application.Command.Traceable;
using B.S.Traceable.Read.Api.Dtos;
using MediatR;

namespace B.S.Traceable.Read.Api.Application.CommandHandler.Traceable
{
    public class FanTraceableHandler : IRequestHandler<FanTraceableCommand, ApiResult<List<TraceableDto>>>
    {
        private readonly IBaseRepository<TraceableModel> traRepo;
        private readonly IMapper mapper;
        private readonly IBaseRepository<ShopModel> shopRepo;

        public FanTraceableHandler(IBaseRepository<TraceableModel> traRepo, IMapper mapper, IBaseRepository<ShopModel> shopRepo)
        {
            this.traRepo = traRepo;
            this.mapper = mapper;
            this.shopRepo = shopRepo;
        }

        public Task<ApiResult<List<TraceableDto>>> Handle(FanTraceableCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<TraceableDto>> result=new ApiResult<List<TraceableDto>>();
            result.Code = ApiEnums.Success;
            result.Msg = "查询成功";
            var s = from a in traRepo.GetAll()
                    join b in shopRepo.GetAll() on a.ShopId equals b.ShopId
                    where a.TraceableId == request.TraceableId && a.IsDeleted == false
                    select new TraceableDto
                    {
                        TraceableId = a.TraceableId,
                        ShopId = b.ShopId,
                        ShopName = b.ShopName,
                        Production_batches = a.Production_batches,
                        Shelf_Life = a.Shelf_Life,
                        Production_License_Number = a.Production_License_Number,
                        Production_Industry = a.Production_Industry,
                        Picture = a.Picture,
                        Information = a.Information,
                        CreateName = a.CreateName,
                        CreateTime = a.CreateTime,
                        UpdateName = a.UpdateName,
                        UpdateTime = a.UpdateTime,
                    };
            result.Data = mapper.Map<List<TraceableDto>>(s);
            return Task.FromResult(result);
        }
    }
}
